﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InventoryManager : MonoBehaviour,IGameManager {

    public ManagerStatus status { get; private set; }

    private Dictionary<string,int> _items;

    public string equippedItem { get; private set; }

    private NetworkService _network;

    public List<string> GetItemList()
    {
        List<string> list = new List<string>(_items.Keys);
        return list;
    }

    public int GetItemCount(string name)
    {
        if (_items.ContainsKey(name))
            return _items[name];
        return 0;
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public void Startup(NetworkService service)
    {
        Debug.Log("Inventory manager starting...");
        //初始化空的物品列表
        _items = new Dictionary<string, int>();

        //初始化一个空列表
        UpdateData(new Dictionary<string, int>());

        status = ManagerStatus.Started;
    }

    //打印当前仓库的控制台消息
    private void DisplayItems()
    {
        string itemDisplay = "Items:";
        foreach (KeyValuePair<string, int> item in _items)
        {
            itemDisplay += item.Key + "(" + item.Value + ")";
        }
        Debug.Log(itemDisplay);
    }

    //其他脚本可以调用但是不能直接操作列表
    public void AddItem(string name)
    {
        //输入新的数据前检查入口是否已经存在
        if (_items.ContainsKey(name))
        {
            _items[name] += 1;
        }
        else
        {
            _items[name] = 1;
        }

        DisplayItems();
    }

    public bool EquipItem(string name)
    {
        //检查仓库中有该物品并且还没有被装备
        if (_items.ContainsKey(name) && equippedItem != name)
        {
            equippedItem = name;
            Debug.Log("Equipped:"+name);
            return true;
        }

        equippedItem = null;
        Debug.Log("Unequipped");
        return false;
    }

    public bool ConsumeItem(string name)
    {
        //检查物品是否在仓库中
        if (_items.ContainsKey(name))
        {
            _items[name]--;
            //如果数量减为0，则移除物品
            if (_items[name] == 0)
            {
                _items.Remove(name);
            }
        }
        //如果仓库中没有该物品，则给出响应
        else
        {
            Debug.Log("cannotconsume" + name);
            return false;
        }

        DisplayItems();
        return true;
    }

    public void UpdateData(Dictionary<string, int> items)
    {
        _items = items;
    }

    //为了保存数据需要getter方法
    public Dictionary<string, int> GetData()
    {
        return _items;
    }
}
